import { Injectable } from '@nestjs/common';
import { ElasticsearchService } from '@nestjs/elasticsearch';
import { PostEntity } from 'src/entity/Entity';
import {pick} from 'lodash'
import { instanceToPlain } from 'class-transformer';
import { PostSearchBody } from 'src/config/defaultconfig';
@Injectable()
export class SearchService {
    index = 'posts';
    constructor(
        protected esService: ElasticsearchService
    ){}
    async search(text:string){
        const {hits}= await this.esService.search<PostEntity>({
            //必须要的索引
            index:this.index,
            query:{
                multi_match:{query:text,fields:['title', 'body', 'summary', 'categories']}
            }

        })


        return hits.hits.map((item)=>item._source)
    }

    //创建文章索引
    async create(post:PostEntity){
        return this.esService.index<PostEntity>({
            index:this.index,
            document:{
                //instanceToPlain 是 class-transformer 库中的一个函数，
                //它的作用是将 JavaScript 对象（即类实例）转换为普通的 JavaScript 对象
                //（即普通的键值对对象）
                ...pick(instanceToPlain(post),['id', 'title', 'body', 'summary']),
                categories:(post.categories??[]).join(',')
            }

        })
    }
async update(post:PostEntity){
    let newBody: PostSearchBody={
        ...pick(instanceToPlain(post),['id', 'title', 'body', 'summary']),
        categories: (post.categories ?? []).join(','),
    }

    
}

}